package com.etoak.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.redis.RedisService;
import com.etoak.common.web.context.LoginContext;
import com.etoak.entity.dto.CartDTO;
import com.etoak.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    RedisService redisService;

    @Override
    public void add(CartDTO cartDTO) {
        redisService.hset(getCartKey(),
                cartDTO.getDishesId().toString(),
                JSONUtil.toJsonStr(cartDTO));
    }

    @Override
    public List<CartDTO> getCartByToken() {
        String cartKey = getCartKey();
        List<String> hvals = redisService.hvals(cartKey);
        List<CartDTO> returnList = new ArrayList<>();
        for (String hval : hvals) {
            CartDTO bean = JSONUtil.toBean(hval, CartDTO.class);
            returnList.add(bean);
        }
        return returnList;
    }

    @Override
    public List<CartDTO> getList() {
        return redisService.hvals(getCartKey())
                .stream()
                .map(cardJson -> JSONUtil.toBean(cardJson, CartDTO.class))
                .toList();
    }

    @Override
    public void deleteDishes(int id) {
        redisService.hdel(getCartKey(), String.valueOf(id));
    }

    @Override
    public void clearCart() {
        redisService.del(getCartKey());
    }

    private String getCartKey() {
        return CommonConstant.REDIS_CART_PREFIEX + LoginContext.getUserId();
    }
}
